package vn.evolus.pencil.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import vn.evolus.commons.data.IRepository;
import vn.evolus.pencil.model.Role;
import vn.evolus.pencil.service.RoleService;

@Transactional(propagation = Propagation.SUPPORTS)
public class RoleServiceImpl implements RoleService {
	
	private static final String ROLE_USER_STRING = "ROLE_USER";
	private static final String ROLE_ADMIN_STRING = "ROLE_ADMIN";
	
	private IRepository repository;

	public RoleServiceImpl(IRepository repository) {
		super();
		this.repository = repository;
	}

	@Override
	public Role getUserRole() {
		return getRoleByName(ROLE_USER_STRING);
	}

	@Override
	@Transactional
	public void createUserRole() {
		createRoleByName(ROLE_USER_STRING);
	}

	@Override
	public Role getAdminRole() {
		return getRoleByName(ROLE_ADMIN_STRING);
	}

	@Override
	@Transactional
	public void createAdminRole() {
		createRoleByName(ROLE_ADMIN_STRING);
	}
	
	private Role getRoleByName(String roleName) {
		return repository.getByKey(Role.class, "name", roleName);
	}
	
	private void createRoleByName(String roleName) {
		Role role = repository.getByKey(Role.class, "name", roleName);
		if (role == null) {
			role = new Role();
			role.setName(roleName);
			repository.save(role);
		}
	}

	@Override
	@Transactional
	public List<Role> getAllRoles() {
		List<Role> allRoles = new ArrayList<Role>();
		allRoles = repository.getAll(Role.class);
		return allRoles;
	}
}